<script lang="ts" setup>
import type { PropType } from "vue";
import { productType } from "@/config/dictionary";
import { deepClone } from "@/utils";
import LimitedPrizeFormItem from "./components/LimitedPrizeFormItem.vue";
import BasePrizeFormItem from "./components/BasePrizeFormItem.vue";
import StockPrizeFormItem from "./components/StockPrizeFormItem.vue";
import SpecSelectFormItem from "./components/SpecSelectFormItem.vue";
import { getProductDetailApi } from "@/api/activity";

const props = defineProps({
  modelValue: {
    type: Object as PropType<any>,
  },
  poolType: {
    type: Number,
    default: 1,
  },
  grantType: {
    type: Number,
    default: -1,
  },
  stock: {
    type: Number,
    default: 0,
  },
});

const emits = defineEmits(["update:modelValue"]),
  activityModel: string = inject("activityModel", "");

const formRef = ref();
const initDescText=ref('')

watch(
  () => props.modelValue.goodsId,
  (val) => {
    nextTick(async () => {
      let detail = await getGoodsDetail(val);
      if (detail) {
        form.value.goodsName = detail.productName;
        form.value.goodsType = detail.productType;
        form.value.goodsStore = detail.storeName;
        initDescText.value = form.value.dir||''
      }
    });
  },
  { immediate: true }
);

const form: any = computed({
  get: () => {
    props.modelValue.prizeSpecifications.forEach((spec: any) => {
      if (spec.originalStock === undefined)
        spec.originalStock = spec.stock || 0;
      if (spec.originalStockTotal === undefined)
        spec.originalStockTotal = spec.totalStock || 0;
    });
    return props.modelValue;
  },
  set: (val) => {
    emits("update:modelValue", val);
  },
});

function validateSpec(rule: any, value: any, callback: any) {
  // 规格预库存不能小于礼品包库存
  let specStock = form.value.prizeSpecifications[this].specStock;
  if (props.grantType === -1 && Number(specStock) < props.stock) {
    callback(new Error("该规格库存小于礼品包库存，请重新选择"));
  }

  callback();
}

function validateSpecStock(rule: any, value: any, callback: any) {
  // 规格库存不能小于礼品包库存
  let stock = form.value.prizeSpecifications[this].stock;
  if (
    form.value.prizeSpecifications[this].onlineStatus == 1 &&
    props.grantType === -1 &&
    Number(stock) < props.stock
  ) {
    callback(new Error("规格库存不能小于礼品包库存"));
  }

  callback();
}

// 获取商品详情
const getGoodsDetail = async (id) => {
  const rs = await getProductDetailApi({ id });
  if (rs.code == 200) return rs.payload;
  return null;
};

const check = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        detail.stock = detail.prizeSpecifications.reduce(
          (total: number, item: any) => {
            if (item.onlineStatus == 0) return total;
            return total + item.stock;
          },
          0
        );
        detail.stockTotal = detail.prizeSpecifications.reduce(
          (total: number, item: any) => {
            if (item.onlineStatus == 0) return total;
            return total + item.totalStock;
          },
          0
        );
        detail.onlineStatus = detail.prizeSpecifications[0].onlineStatus;

        resolve(detail);
      } else reject("");
    });
  });
};

const onChange = () => {
  form.value = form.value;
};
const handleTextChange=({innerHTML}:{innerHTML:string})=>{
  form.value.dir=innerHTML
}

provide("formRef", formRef);

defineExpose({ check });
</script>
<template>
  <el-form ref="formRef" :model="form" label-width="auto">
    <div class="product-info">
      <span>商品名称：{{ form.goodsName }}</span>
      <span>商品类型：{{ productType[form.goodsType] }}</span>
      <span>所属商家：{{ form.goodsStore }}</span>
    </div>
    <template v-for="(spec, index) in form.prizeSpecifications">
      <SpecSelectFormItem
        v-model="form.prizeSpecifications[index]"
        :disabled="form.id !== undefined"
        :goodsId="form.goodsId"
        :prefix="`prizeSpecifications.${index}.`"
        :rules="[
          {
            validator: validateSpec.bind(index),
            trigger: 'change',
          },
        ]"
      />
      <BasePrizeFormItem
        v-model="form.prizeSpecifications[index]"
        :prefix="`prizeSpecifications.${index}.`"
        :label="['规格名称', '规格图片']"
      />
      <StockPrizeFormItem
        v-if="activityModel !== 'edit' || form.id === undefined"
        v-model="form.prizeSpecifications[index]"
        :prefix="`prizeSpecifications.${index}.`"
        :rules="[
          {
            validator: validateSpecStock.bind(index),
            trigger: 'blur',
          },
        ]"
      />
      <el-form-item
        label="状态:"
        :prop="`prizeSpecifications.${index}.onlineStatus`"
        v-if="activityModel !== 'edit' || form.id === undefined"
      >
        <el-switch
          v-model="spec.onlineStatus"
          inline-prompt
          active-text="上架"
          inactive-text="下架"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </template>
    <!-- 限制条件 -->
    <LimitedPrizeFormItem
      v-model="form"
      :poolType="poolType"
      :type="form.type"
    />
    <el-form-item
      label="使用说明:"
      prop="dir"
      :rules="[
        { required: true, message: `请填写使用说明`, trigger: 'change' },
      ]"
    >
      <!-- <el-input
        v-model="form.dir"
        :autosize="{ minRows: 4 }"
        maxlength="500"
        show-word-limit
        type="textarea"
        placeholder="请填写使用说明"
      /> -->
      <rich-editor :id-name="`gift-bag-${new Date().getTime()}`" :initial-value="initDescText" @change="handleTextChange"></rich-editor>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.product-info {
  margin-bottom: 20px;
  span {
    + span {
      margin-left: 20px;
    }
  }
}
</style>
